var roles = {};
var unitArray = [];
$(document).ready(function() {
    getUserInfo();
    $('#headerUserName').append('<a href="profile.html"><i class="icon-user"></i> ' + viewData.user.hsaId + '</a>');
    $('#mastHead').append('<h2>Profil</h2>' + viewData.user.realname);

    jQuery.validator.addMethod('requiredIfEmpty', function(value, element, param) {
        var target = $(param);
        var valid = target.val() !== '' || value !== '';
        return valid;
    });

    $('#bUpdateUser').click(function() {
        $('#edit-profile').validate({
            rules: {
                name: "required",
                email: "required",
                passwordNewConfirm: {
                    equalTo: "#passwordNew"
                },
                newEmail: {
                    requiredIfEmpty: "#email"
                },
                confirmNewEmail: {
                    equalTo: "#newEmail"
                }
            },
            messages: {
                name: "Fyll i namn",
                email: "Fyll i E-postadress",
                passwordNewConfirm: {
                    equalTo: "Lösenorden överensstämmer inte"
                },
                newEmail: {
                    requiredIfEmpty: "Du måste ange en e-postadress"
                },
                confirmNewEmail: {
                    equalTo: "E-postadresserna överensstämmer inte"
                }
            }
        });
    });
});

$('#edit-profile').submit(function(event) {
    if ($('#edit-profile').valid()) {
        var role = $('#userrole').val();
        var userName = $('#username').val();
        var name = $('#name').val();

        var email = $('#email').val();
        var newEmail = $('#newEmail').val();
        if (newEmail !== '') {
            email = newEmail;
        }

        var newPasswordRaw = $('#passwordNew').val();
        var newPassword = newPasswordRaw !== '' ? newPasswordRaw : null;
        updateUser(name, userName, email, role, newPassword);
    }
    event.preventDefault();
});

function getUserInfo() {
    $('#username').val(viewData.user.hsaId);
    $('#name').val(viewData.user.realname);
    $('#email').val(viewData.user.email);
    $('#userrole').val(renderRole(viewData.user.role));
}

function updateUser(realName, userName, email, role, password) {
    var data = {
        "realname": realName,
        "email": email,
        "hsaId": userName,
        "password": password,
        "status": "ACTIVE",
        "role": viewData.user.role,
        "careUnitID": viewData.user.careUnits
    };
    var theURL = config.guiURL + '/users/' + userName;
    $.ajax({
        url: theURL,
        type: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json',
        async: false,
        success: function(msg) {
            showGrowlMessage('Profil uppdaterad.');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            showErrorGrowlMessage(jqXHR.responseText);
            if (textStatus==='error' && errorThrown==='Unauthorized') {
                alert("Din användarsession har gått ut, du måste logga in på nytt!")
                $(location).attr('href','../');
            }
        }
    });
}

function renderRole(data, type, full) {
    return viewData.roles[data];
}

function showGrowlMessage(sText) {
    $.msgGrowl({
        type: 'success',
        title: 'OK',
        text: sText
    });
}

function showErrorGrowlMessage(sText) {
    $.msgGrowl({
        type: 'error',
        title: 'FEL',
        text: sText,
        sticky: true
    });
}
